#include "UserManager.h"

#include <QDir>
#include <QFile>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardPaths>

UserManager::UserManager(QObject *parent)
    : QObject{parent}
    , m_name{""}
    , m_level{0}
    , m_availablePoints{0}
    , m_todayPoints{0}
    , m_totalPoints{0}
{
    // 检查数据文件是否存在
    QFile file(getDataFilePath());

    if (file.exists()) {
        // 文件存在，从文件加载数据
        if (!loadFromJsonFile()) {
            qWarning() << "Failed to load user data from file, initializing with default values";
            initializeDefaultData();
            createInitialJsonFile();
        }
    } else {
        // 文件不存在，初始化默认数据并创建文件
        initializeDefaultData();
        createInitialJsonFile();
    }
}
void UserManager::pointsIncrease(int points)
{
    // 使用 setter 方法以确保发出信号
    setAvailablePoints(m_availablePoints + points);
    setTotalPoints(m_totalPoints + points);
    setTodayPoints(m_todayPoints + points);

    // 立即保存用户数据
    saveUserData();
}

void UserManager::pointsDecrease(int points)
{
    // 使用 setter 方法以确保发出信号
    setAvailablePoints(m_availablePoints - points);
    setTotalPoints(m_totalPoints - points);

    // 立即保存用户数据
    saveUserData();
}
void UserManager::saveUserData()
{
    QJsonObject jsonObj;
    jsonObj["name"] = m_name;
    jsonObj["level"] = m_level;
    jsonObj["availablePoints"] = m_availablePoints;
    jsonObj["todayPoints"] = m_todayPoints;
    jsonObj["totalPoints"] = m_totalPoints;

    QJsonDocument doc(jsonObj);
    QFile file(getDataFilePath());

    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson());
        file.close();
        qDebug() << "User data saved successfully";
    } else {
        qWarning() << "Failed to save user data:" << file.errorString();
    }
}

void UserManager::loadUserData()
{
    if (!loadFromJsonFile()) {
        qWarning() << "Failed to load user data";
    }
}

void UserManager::initializeDefaultData()
{
    m_name = "";
    m_level = 0;
    m_availablePoints = 0;
    m_todayPoints = 0;
    m_totalPoints = 0;
}

QString UserManager::getDataFilePath() const
{
    // 使用应用程序数据目录
    QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataDir);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    return dir.filePath("userdata.json");
}

void UserManager::createInitialJsonFile()
{
    QJsonObject jsonObj;
    jsonObj["name"] = m_name;
    jsonObj["level"] = m_level;
    jsonObj["availablePoints"] = m_availablePoints;
    jsonObj["todayPoints"] = m_todayPoints;
    jsonObj["totalPoints"] = m_totalPoints;

    QJsonDocument doc(jsonObj);
    QFile file(getDataFilePath());

    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson());
        file.close();
        qDebug() << "Initial user data file created successfully";
    } else {
        qWarning() << "Failed to create initial user data file:" << file.errorString();
    }
}

bool UserManager::loadFromJsonFile()
{
    QFile file(getDataFilePath());
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to open user data file for reading:" << file.errorString();
        return false;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull() || !doc.isObject()) {
        qWarning() << "Invalid JSON format in user data file";
        return false;
    }

    QJsonObject jsonObj = doc.object();

    // 从 JSON 加载数据
    m_name = jsonObj["name"].toString("");
    m_level = jsonObj["level"].toInt(0);
    m_availablePoints = jsonObj["availablePoints"].toInt(0);
    m_todayPoints = jsonObj["todayPoints"].toInt(0);
    m_totalPoints = jsonObj["totalPoints"].toInt(0);

    qDebug() << "User data loaded successfully from file";
    return true;
}
